package com.evanp.centre.good.controller;

import com.evanp.centre.good.model.po.Good;
import com.evanp.centre.good.model.vo.GoodVo;
import com.evanp.centre.good.model.vo.SimpleGoodVo;
import com.evanp.centre.good.service.GoodService;
import com.evanp.centre.util.ResBuilder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/inside/good")
public class GoodInsideApiController {
    @Resource
    private GoodService goodService;

    /**
     * 简单商品Vo查询接口
     * @param body {gids: string[]}
     * @return RespMap
     */
    @PostMapping("/sel/gids")
    public Map query_goodvo_by_gids(@RequestBody HashMap<String, Object> body){
        System.out.println(body);
        ArrayList<String> gids = (ArrayList<String>) body.get("gids");
        System.out.println(gids);
        List<SimpleGoodVo> goodVos = goodService.sel_simple_good_by_gids(gids);
        return ResBuilder.ok("查询成功", 0, goodVos);
    }

    /*
     * @Author Evanpatchouli
     * @see <a href="http://localhost:8080/inner/good/add-storage?gid=?&num=?">增加某商品库存接口</a>
     * @Description 增加某商品库存接口，接收2个路径参数
     * @Param gid 商品id
     * @Param num 变动数量
     * @Return Result code:200成功,gstorage:更新后的储量
     * */
    @RequestMapping("/add-storage")
    public Map increaseGoodNum(@RequestParam String gid,@RequestParam int num){
        Good good = goodService.sel_one_by_gid(gid);
        if (good==null){
            return ResBuilder.fail("商品不存在", 0);
        }
        goodService.add_store_by_gid(num,gid);
        int storage = goodService.sel_store_by_gid(gid);
        Map data = new HashMap();
        data.put("storage",storage);
        return ResBuilder.ok("库存已增加", 0, data);
    }

    /*
     * @Author Evanpatchouli
     * @see <a href="http://localhost:8080/inner/good/cut-storage?gid=?&num=?">减少某商品库存接口</a>
     * @Description 减少某商品库存接口，接收2个路径参数，会检查库存是否够扣这么多
     * @Param gid 商品id
     * @Param num 变动数量
     * @Return Result code:200成功，400失败,gstorage:更新后的储量
     * */
    @RequestMapping("/cut-storage")
    public Map decreaseGoodNum(@RequestParam String gid,@RequestParam int num){
        Good good = goodService.sel_one_by_gid(gid);
        if (good==null){
            return ResBuilder.fail("商品不存在", 0);
        }
        Map data = new HashMap();
        int storage = goodService.sel_store_by_gid(gid);
        int delta = num;
        if(storage-delta<0){
            data.put("gstorage",storage);
            return ResBuilder.fail("库存不足", 0, data);
        }
        goodService.cut_store_by_gid(delta, gid);
        data.put("gstorage",storage-delta);
        return ResBuilder.ok("库存成功减少", 0, data);
    }

}
